<!DOCTYPE html>
<html class="has-navbar-fixed-top">
<head>
    <meta charset="utf-8">
<title>使用POI替换Word模板中的关键词 - wanzixin</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.css">


<link href="/Item/zh-cn/%E4%BD%BF%E7%94%A8POI%E6%9B%BF%E6%8D%A2Word%E6%A8%A1%E6%9D%BF%E4%B8%AD%E7%9A%84%E5%85%B3%E9%94%AE%E8%AF%8D/" rel="alternate" hreflang="en" />
    


<meta name="description" content="">





    <meta name="description" content="这里的POI不是Point Of Interest兴趣点，而是针对Microsoft Documents的开源Java API，当前最新版本是4.1.2，官网指路。Word模板格式是.docx，所以重点讨论POI中的XWPFDocument。JDK版本是JDK 14。IDE使用IntelliJ IDEA 2020.1.2。">
<meta property="og:type" content="article">
<meta property="og:title" content="使用POI替换Word模板中的关键词">
<meta property="og:url" content="https://wanzixin.github.io/Item/zh-cn/%E4%BD%BF%E7%94%A8POI%E6%9B%BF%E6%8D%A2Word%E6%A8%A1%E6%9D%BF%E4%B8%AD%E7%9A%84%E5%85%B3%E9%94%AE%E8%AF%8D/index.html">
<meta property="og:site_name" content="wanzixin">
<meta property="og:description" content="这里的POI不是Point Of Interest兴趣点，而是针对Microsoft Documents的开源Java API，当前最新版本是4.1.2，官网指路。Word模板格式是.docx，所以重点讨论POI中的XWPFDocument。JDK版本是JDK 14。IDE使用IntelliJ IDEA 2020.1.2。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-10T14:23:34.000Z">
<meta property="article:modified_time" content="2021-05-30T14:24:19.748Z">
<meta property="article:author" content="wanzixin">
<meta name="twitter:card" content="summary">





<link rel="icon" href="/favicon.png">


<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Ovo|Source+Code+Pro">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">


<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/css/lightgallery.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/css/justifiedGallery.min.css">


<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-light.min.css">


<link rel="stylesheet" href="/css/style.css">


<script defer src="//use.fontawesome.com/releases/v5.0.8/js/all.js"></script>


    
    
    
    
    
    
    
    
    
    

    


<meta name="generator" content="Hexo 5.4.0"></head>
<body>
    
<nav class="navbar is-transparent is-fixed-top navbar-main" role="navigation" aria-label="main navigation">
    <div class="container">
        <div class="navbar-brand">
            <a class="navbar-item navbar-logo" href="/zh-cn">
                
                    
                    wanzixin
                    
                
            </a>
            <div class="navbar-burger">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
        
        <div class="navbar-menu navbar-start">
            
            <a class="navbar-item "
               href="/archives">Archives</a>
            
            <a class="navbar-item "
               href="/categories">Categories</a>
            
            <a class="navbar-item "
               href="/categories/Diary">Diary</a>
            
            <a class="navbar-item "
               href="/categories/Gallery">Gallery</a>
            
            <a class="navbar-item "
               href="/categories/Study">Study</a>
            
            <a class="navbar-item "
               href="/categories/Item">Item</a>
            
            <a class="navbar-item "
               href="/about">About</a>
            
        </div>
        
        <div class="navbar-menu navbar-end">
            
            <a class="navbar-item search" title="搜索" href="javascript:;">
                <i class="fas fa-search"></i>
            </a>
            
            
            <div class="navbar-item is-hoverable has-dropdown is-hidden-mobile is-hidden-tablet-only toc">
                <a class="navbar-item" title="目录">
                    <i class="fa fa-list"></i>
                </a>
                <div class="navbar-dropdown is-right">
                    
                    
                    
                    
                    <a class="navbar-item" href="#从数据库提取信息">1&nbsp;&nbsp;<b>从数据库提取信息</b></a>
                    
                    
                    <hr class="navbar-divider">
                    
                    
                    <a class="navbar-item" href="#替换模板中的关键词">2&nbsp;&nbsp;<b>替换模板中的关键词</b></a>
                    
                    
                    <hr class="navbar-divider">
                    
                    
                    <a class="navbar-item" href="#合并文档">3&nbsp;&nbsp;<b>合并文档</b></a>
                    
                    
                    <hr class="navbar-divider">
                    
                    
                    <a class="navbar-item" href="#结束语">4&nbsp;&nbsp;<b>结束语</b></a>
                    
                </div>
            </div>
            
            
            <a class="navbar-item" title="GitHub" target="_blank" rel="noopener" href="https://github.com/wanzixin">
                
                <i class="fab fa-github"></i>
                
            </a>
               
            
        </div>
    </div>
</nav>

    <section class="section">
    <div class="container">
    <article class="article content gallery" itemscope itemprop="blogPost">
    <h1 class="article-title is-size-3 is-size-4-mobile" itemprop="name">
        
            使用POI替换Word模板中的关键词
        
    </h1>
    <div class="article-meta columns is-variable is-1 is-multiline is-mobile is-size-7-mobile">
        <span class="column is-narrow">
            
                <span>7月 10 2020</span>
            
        </span>
        
        <span class="column is-narrow article-category">
            <i class="far fa-folder"></i>
            <a class="article-category-link" href="/zh-cn/categories/Item/">Item</a>
        </span>
        
        
        <span class="column is-narrow">
            
            
            10 分钟 读完 (约 1551 字)
        </span>
        
    </div>
    <div class="article-entry is-size-6-mobile" itemprop="articleBody">
    
        <html><head></head><body><p>这里的POI不是Point Of Interest兴趣点，而是针对Microsoft Documents的开源Java API，当前最新版本是4.1.2，官网<a target="_blank" rel="noopener" href="http://poi.apache.org/">指路</a>。Word模板格式是<code>.docx</code>，所以重点讨论POI中的XWPFDocument。JDK版本是JDK 14。IDE使用IntelliJ IDEA 2020.1.2。<span id="more"></span></p>
<h2 id="从数据库提取信息"><a href="#从数据库提取信息" class="headerlink" title="从数据库提取信息"></a>从数据库提取信息</h2><p>首先，连接Oracle数据库，查看待操作表的字段，拟定sql语句在查询窗口运行查看结果。然后，导入ojdbc10.jar和fastjson*-1.2.7.*jar，编写代码连接数据库并执行查询语句，组合每一个JSONObject，构造JSONArray返回。这个JSONArray中的键值对用来替换Word模板中的关键词。</p>
<figure class="highlight java hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 连接数据库，查询的代码</span><br><span class="hljs-keyword">package</span> ManipulateDB;<br><br><span class="hljs-keyword">import</span> com.alibaba.fastjson.JSONArray;<br><span class="hljs-keyword">import</span> com.alibaba.fastjson.JSONObject;<br><span class="hljs-keyword">import</span> java.sql.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OracleDB</span> </span>{<br>    <span class="hljs-keyword">private</span> String url = <span class="hljs-string">"jdbc:oracle:thin:@ip地址:端口号:SID"</span>;<br>    <span class="hljs-keyword">private</span> String username = <span class="hljs-string">"your_name"</span>;<br>    <span class="hljs-keyword">private</span> String password = <span class="hljs-string">"your_password"</span>;<br>    <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 连接oracle数据库</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 返回Connection实例</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Connection <span class="hljs-title">getConnect</span><span class="hljs-params">()</span></span>{<br>        Connection connect = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">try</span>{<br>            <span class="hljs-comment">//建立驱动</span><br>            String driverName = <span class="hljs-string">"oracle.jdbc.driver.OracleDriver"</span>;<br>            Class.forName(driverName);<br>            <span class="hljs-comment">//连接</span><br>            connect = DriverManager.getConnection(url, username, password);<br>        }<span class="hljs-keyword">catch</span> (Exception e){<br>            e.printStackTrace();<br>        }<br>        <span class="hljs-keyword">return</span> connect;<br>    }<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据TBYBH编号查询DLTB表获取信息：编号，坐落，面积，地类编码，地类名称</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> idStr</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 返回一个JSONArray，包含上述信息</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> JSONArray <span class="hljs-title">query</span><span class="hljs-params">(String idStr)</span> <span class="hljs-keyword">throws</span> Exception</span>{<br>        JSONArray infos = <span class="hljs-keyword">new</span> JSONArray();<br>        <span class="hljs-keyword">try</span>{<br>            Connection connect = getConnect();<br>            Statement stmt = connect.createStatement();<br>            String sql = <span class="hljs-string">"select TBYBH,ZLDWDM,ZLDWMC,SHAPE_AREA_1,SHDLBM,SHDLMC from DLTB where TBYBH= '"</span>+idStr+<span class="hljs-string">"'"</span>;<br>            ResultSet rs = stmt.executeQuery(sql);<br><br>            <span class="hljs-keyword">while</span>(rs.next()){<br>                String TBYBH = rs.getString(<span class="hljs-string">"TBYBH"</span>);<br>                String ZLDWDM = rs.getString(<span class="hljs-string">"ZLDWDM"</span>).substring(<span class="hljs-number">0</span>,<span class="hljs-number">12</span>);<span class="hljs-comment">//截取前12位</span><br>                <span class="hljs-keyword">int</span> SHAPE_AREA_1 = (<span class="hljs-keyword">int</span>)Math.floor(rs.getInt(<span class="hljs-string">"SHAPE_AREA_1"</span>));<span class="hljs-comment">//保留整数位</span><br>                String SHDLBM = rs.getString(<span class="hljs-string">"SHDLBM"</span>);<br>                String SHDLMC = rs.getString(<span class="hljs-string">"SHDLMC"</span>);<br>                String country = rs.getString(<span class="hljs-string">"ZLDWMC"</span>);<br><br>                String address = <span class="hljs-keyword">this</span>.queryAddress(ZLDWDM.substring(<span class="hljs-number">0</span>,<span class="hljs-number">6</span>));<br>                address += <span class="hljs-keyword">this</span>.queryAddress(ZLDWDM.substring(<span class="hljs-number">0</span>,<span class="hljs-number">9</span>));<br>                address += country;<br><br>                JSONObject info = <span class="hljs-keyword">new</span> JSONObject();<br>                info.put(<span class="hljs-string">"TBYBH"</span>,TBYBH);<br>                info.put(<span class="hljs-string">"ZLDWDM"</span>,ZLDWDM);<br>                info.put(<span class="hljs-string">"SHAPE_AREA_1"</span>,SHAPE_AREA_1);<br>                info.put(<span class="hljs-string">"SHDLBM"</span>,SHDLBM);<br>                info.put(<span class="hljs-string">"SHDLMC"</span>,SHDLMC);<br>                info.put(<span class="hljs-string">"ADDRESS"</span>,address);<br><br>                infos.add(info);<br>            }<br><br>            <span class="hljs-comment">// 数据库查询后一定要关闭资源，不然数据库会限制连接数目，从而中断程序</span><br>            connect.close();<br>            stmt.close();<br>            rs.close();<br>        }<span class="hljs-keyword">catch</span> (SQLException e){<br>            e.printStackTrace();<br>        }<br>        <span class="hljs-keyword">return</span> infos;<br>    }<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception</span>{<br>        OracleDB orcltool = <span class="hljs-keyword">new</span> OracleDB();<br>        JSONArray infos = orcltool.query(<span class="hljs-string">"310117120F04318"</span>);<br>        System.out.println(infos);<br>    }<br></code></pre></td></tr></tbody></table></figure>
<h2 id="替换模板中的关键词"><a href="#替换模板中的关键词" class="headerlink" title="替换模板中的关键词"></a>替换模板中的关键词</h2><p>POI结构说明如下，更多信息查看Components，地址<a target="_blank" rel="noopener" href="http://poi.apache.org/components/index.html">指路</a>。</p>
<table>
<thead>
<tr>
<th align="center">名称</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">HSSF</td>
<td align="center">读写Excel .xls格式文档</td>
</tr>
<tr>
<td align="center">XSSF</td>
<td align="center">读写Excel .xlsx格式文档</td>
</tr>
<tr>
<td align="center">HWPF</td>
<td align="center">读写Word.doc格式文档</td>
</tr>
<tr>
<td align="center">XWPF</td>
<td align="center">读写Word.docx格式文档</td>
</tr>
<tr>
<td align="center">HSLF</td>
<td align="center">读写PPT.ppt格式文档</td>
</tr>
<tr>
<td align="center">XLSF</td>
<td align="center">读写PPT.pptx格式文档</td>
</tr>
</tbody></table>
<p>本文的模板文档格式是<code>.docx</code>，主体是一个表格，于是遍历每一个单元格，若匹配到关键词，则删除原有文本，填入自定义文本。没错，XWPFDocument没有提供replace之类的api，只能删除原有文本再填入新文本。<code>.docx</code>文档实际上是一个压缩包。若加载多媒体资源，比如图片时，如果没有展示出来，可以将后缀名改为.zip再解压便可以看到内部结构，查看多媒体资源是否写入成功。</p>
<figure class="highlight java hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><code class="hljs java">  <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 替换对应信息</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@param</span> docx</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@param</span> info</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">    */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">replaceInTable</span><span class="hljs-params">(XWPFDocument docx,JSONObject info)</span> <span class="hljs-keyword">throws</span> Exception</span>{<br>       List&lt;XWPFTable&gt; tables = docx.getTables();<br>       XWPFTable table = tables.get(tables.size()-<span class="hljs-number">1</span>);<br>       List&lt;XWPFTableRow&gt; rows;<br>       List&lt;XWPFTableCell&gt; cells;<br><br>       rows = table.getRows();<br>       <span class="hljs-keyword">for</span> (XWPFTableRow row : rows) {<br>           cells = row.getTableCells();<br>           <span class="hljs-keyword">for</span> (XWPFTableCell cell : cells) {<br>               String text = cell.getText();<br>               <span class="hljs-keyword">if</span>(text.equals(<span class="hljs-string">"TBYBH"</span>)){<br>                   cell.removeParagraph(<span class="hljs-number">0</span>);<br>                   cell.setText(info.getString(<span class="hljs-string">"TBYBH"</span>));<br>                   System.out.println(<span class="hljs-string">"TBYBH修改成功:  "</span>+info.getString(<span class="hljs-string">"TBYBH"</span>));<br>               }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(text.equals(<span class="hljs-string">"ZLDWDM"</span>)){<br>                   cell.removeParagraph(<span class="hljs-number">0</span>);<br>                   cell.setText(info.getString(<span class="hljs-string">"ADDRESS"</span>));<br>               }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(text.equals(<span class="hljs-string">"SHAPE_AREA_1"</span>)){<br>                   cell.removeParagraph(<span class="hljs-number">0</span>);<br>                   cell.setText(info.getString(<span class="hljs-string">"SHAPE_AREA_1"</span>));<br>               }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(text.equals(<span class="hljs-string">"SHDLBM"</span>)){<br>                   cell.removeParagraph(<span class="hljs-number">0</span>);<br>                   cell.setText(info.getString(<span class="hljs-string">"SHDLBM"</span>));<br>               }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (text.equals(<span class="hljs-string">"SHDLMC"</span>)){<br>                   cell.removeParagraph(<span class="hljs-number">0</span>);<br>                   cell.setText(info.getString(<span class="hljs-string">"SHDLMC"</span>));<br>               }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(text.equals(<span class="hljs-string">"picture"</span>)){<br>                   <span class="hljs-keyword">this</span>.addPics(cell,info.getString(<span class="hljs-string">"TBYBH"</span>));<br>               }<br>           }<br>       }<br>   }<br><br>  <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 删除cell原内容，添加图片</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@param</span> cell</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@param</span> TBYBH</span><br><span class="hljs-comment">    * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addPics</span><span class="hljs-params">(XWPFTableCell cell,String TBYBH)</span><span class="hljs-keyword">throws</span> Exception</span>{<br>       cell.removeParagraph(<span class="hljs-number">0</span>);<br>       XWPFParagraph paragraph = cell.addParagraph();<br>       XWPFRun run = paragraph.createRun();<br>       run.setText(<span class="hljs-string">"现场照片："</span>);<br>       run.addBreak();<br><br>       String picspath = <span class="hljs-keyword">this</span>.dirpath+<span class="hljs-string">"\\"</span>+TBYBH;<br>       String[] pics = <span class="hljs-keyword">new</span> File(picspath).list();<br>       <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">4</span> &amp;&amp; i&lt;pics.length;i++){<br>           InputStream is = <span class="hljs-keyword">new</span> FileInputStream(picspath+<span class="hljs-string">"\\"</span>+pics[i]);<br>           <span class="hljs-keyword">if</span>(i == <span class="hljs-number">0</span>){<br>               run.setText(<span class="hljs-string">"图一："</span>);<br>           }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(i == <span class="hljs-number">1</span>){<br>               run.setText(<span class="hljs-string">"图二："</span>);<br>           }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(i == <span class="hljs-number">2</span>){<br>               run.addBreak();<br>               run.setText(<span class="hljs-string">"图三："</span>);<br>           }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(i == <span class="hljs-number">3</span>){<br>               run.setText(<span class="hljs-string">"图四："</span>);<br>           }<br>           run.addPicture(is,XWPFDocument.PICTURE_TYPE_JPEG,pics[i], Units.toEMU(<span class="hljs-number">140</span>),Units.toEMU(<span class="hljs-number">140</span>));<br>           run.setText(<span class="hljs-string">" "</span>);<br>           is.close();<br>       }<br>   }<br></code></pre></td></tr></tbody></table></figure>

<h2 id="合并文档"><a href="#合并文档" class="headerlink" title="合并文档"></a>合并文档</h2><p>一个一个word文档打印起来要点击很多次，于是选择合并为一个文档。选择使用Python的win32模块，注意导入相关依赖。待合并的word文档统一放进一个文件夹，再指定目的文档地址即可。</p>
<figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># author：EduTech</span><br><span class="hljs-comment"># link：https://zhuanlan.zhihu.com/p/100588511</span><br><br><span class="hljs-comment"># 依赖：</span><br><span class="hljs-comment"># pip install pywin32</span><br><span class="hljs-comment"># pip install pypiwin32</span><br><br><span class="hljs-keyword">import</span> win32com.client <span class="hljs-keyword">as</span> win32<br><span class="hljs-keyword">import</span> os<br>word = win32.gencache.EnsureDispatch(<span class="hljs-string">'Word.Application'</span>)<br><span class="hljs-comment">#启动word对象应用</span><br>word.Visible = <span class="hljs-literal">False</span><br>path = <span class="hljs-string">r'D:\software\doc'</span><br>files = []<br><span class="hljs-keyword">for</span> filename <span class="hljs-keyword">in</span> os.listdir(path):<br>    filename = os.path.join(path,filename)<br>    files.append(filename)<br><span class="hljs-comment">#新建合并后的文档</span><br>output = word.Documents.Add()<br><span class="hljs-keyword">for</span> file <span class="hljs-keyword">in</span> files:<br>    output.Application.Selection.InsertFile(file)<span class="hljs-comment">#拼接文档</span><br><span class="hljs-comment">#获取合并后文档的内容</span><br>doc = output.Range(output.Content.Start, output.Content.End)<br>output.SaveAs(<span class="hljs-string">'D://software//doc//result.docx'</span>) <span class="hljs-comment">#保存</span><br>output.Close()<br></code></pre></td></tr></tbody></table></figure>

<h2 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a>结束语</h2><p>整个项目从下载IDEA开始，中间经历了数据库用户名称密码错误，破解IDEA，熟悉IDEA，下载JDK14，POI依赖包的查找，doc转docx，查阅POI官方文档，查找前人博客等一系列问题，直到生成最终的文档，总共花费了三天时间。其中有一天半的时间都卡在怎么样复制旧表格添加到文档末尾，全英文的官方文档看的我头大，越看越急躁，越静不下心来。回想起花了两三个小时看完pyshp优美的官方文档，讲的细致而且举例丰富，IDLE直接可以上手尝试，哪怕是全英文也理解的非常快。下次我学习官方文档的时候，就开着IDEA建一个项目试它的API，应该效果会好很多。</p>
<p>IDEA的界面做的比MyEclipse好看多了。</p>
<p>Word文档的结构好复杂，写一份好看的word文档要花好多时间，希望将来能流行用简单又美观的Markdown文档。</p>
<p>欢迎联系我<a href="mailto:347335189@qq.com">347335189@qq.com</a>。</p>
<p>看得开心!</p>
</body></html>
    
    </div>
    
    
    <div class="columns is-mobile is-multiline article-nav">
        <span class="column is-12-mobile is-half-desktop  article-nav-prev">
            
            <a href="/Item/zh-cn/%E5%8F%B0%E9%A3%8E%E9%A1%B9%E7%9B%AE%E5%9B%9E%E9%A1%BE/">台风项目回顾</a>
            
        </span>
        <span class="column is-12-mobile is-half-desktop  article-nav-next">
            
            <a href="/Item/zh-cn/%E4%BD%BF%E7%94%A8%E9%AB%98%E5%BE%B7Web%E6%9C%8D%E5%8A%A1API%E7%94%9F%E6%88%90shp%E6%96%87%E4%BB%B6/">使用高德Web服务API生成shp文件</a>
            
        </span>
    </div>
    
</article>


<div class="sharebox">
    
<div class="sharethis-inline-share-buttons"></div>
<script type='text/javascript' src='//platform-api.sharethis.com/js/sharethis.js#property=608c1408daac690012507aa2&amp;product=sop' async='async'></script>

</div>



    </div>
</section>
    <footer class="footer">
    <div class="container">
        <div class="columns content">
            <div class="column is-narrow has-text-centered">
                &copy; 2021 wanzixin&nbsp;
                Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> & <a
                        target="_blank" rel="noopener" href="http://github.com/ppoffice/hexo-theme-minos">Minos</a>
            </div>
            <div class="column is-hidden-mobile"></div>

            
            <div class="column is-narrow">
                <div class="columns is-mobile is-multiline is-centered">
                
                    
                <a class="column is-narrow has-text-black" title="GitHub" target="_blank" rel="noopener" href="https://github.com/ppoffice/hexo-theme-minos">
                    
                    GitHub
                    
                </a>
                
                </div>
            </div>
            
            
<div class="column is-narrow has-text-centered">
    <div class="dropdown is-up is-right is-hoverable" style="margin-top: -0.2em;">
        <div class="dropdown-trigger">
            <button class="button is-small" aria-haspopup="true" aria-controls="dropdown-menu7">
                <span class="icon">
                    <i class="fas fa-globe"></i>
                </span>
                <span>简体中文</span>
                <span class="icon is-small">
            <i class="fas fa-angle-down" aria-hidden="true"></i>
          </span>
            </button>
        </div>
        <div class="dropdown-menu has-text-left" role="menu">
            <div class="dropdown-content">
            
                <a href="/Item/zh-cn/%E4%BD%BF%E7%94%A8POI%E6%9B%BF%E6%8D%A2Word%E6%A8%A1%E6%9D%BF%E4%B8%AD%E7%9A%84%E5%85%B3%E9%94%AE%E8%AF%8D/" class="dropdown-item">
                    English
                </a>
            
                <a href="/zh-cn/Item/zh-cn/%E4%BD%BF%E7%94%A8POI%E6%9B%BF%E6%8D%A2Word%E6%A8%A1%E6%9D%BF%E4%B8%AD%E7%9A%84%E5%85%B3%E9%94%AE%E8%AF%8D/" class="dropdown-item">
                    简体中文
                </a>
            
            </div>
        </div>
    </div>
</div>

        </div>
    </div>
</footer>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>

<!-- test if the browser is outdated -->
<div id="outdated">
    <h6>Your browser is out-of-date!</h6>
    <p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" target="_blank" rel="noopener" href="http://outdatedbrowser.com/">Update my browser now </a></p>
    <p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.js"></script>
<script>
    $(document).ready(function () {
        // plugin function, place inside DOM ready function
        outdatedBrowser({
            bgColor: '#f25648',
            color: '#ffffff',
            lowerThan: 'flex'
        })
    });
</script>

<script>
    window.FontAwesomeConfig = {
        searchPseudoElements: true
    }
    moment.locale("zh-CN");
</script>


    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML"></script>
<script>
    MathJax.Hub.Config({
        "HTML-CSS": {
            matchFontHeight: false
        },
        SVG: {
            matchFontHeight: false
        },
        CommonHTML: {
            matchFontHeight: false
        },
        tex2jax: {
            inlineMath: [
                ['$','$'],
                ['\\(','\\)']
            ]
        }
    });
</script>

    
    
    
    
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/js/lightgallery-all.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/js/jquery.justifiedGallery.min.js"></script>
<script>
    (function ($) {
        $(document).ready(function () {
            if (typeof($.fn.lightGallery) === 'function') {
                $('.article.gallery').lightGallery({ selector: '.gallery-item' });
            }
            if (typeof($.fn.justifiedGallery) === 'function') {
                $('.justified-gallery').justifiedGallery();
            }
        });
    })(jQuery);
</script>

    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
    <style>
        .hljs {
            position: relative;
        }

        .hljs .clipboard-btn {
            float: right;
            color: #9a9a9a;
            background: none;
            border: none;
            cursor: pointer;
        }

        .hljs .clipboard-btn:hover {
          color: #8a8a8a;
        }

        .hljs > .clipboard-btn {
            display: none;
            position: absolute;
            right: 4px;
            top: 4px;
        }

        .hljs:hover > .clipboard-btn {
            display: inline;
        }

        .hljs > figcaption > .clipboard-btn {
            margin-right: 4px;
        }
    </style>
    <script>
      $(document).ready(function () {
        $('figure.hljs').each(function(i, figure) {
          var codeId = 'code-' + i;
          var code = figure.querySelector('.code');
          var copyButton = $('<button>Copy <i class="far fa-clipboard"></i></button>');
          code.id = codeId;
          copyButton.addClass('clipboard-btn');
          copyButton.attr('data-clipboard-target-id', codeId);

          var figcaption = figure.querySelector('figcaption');

          if (figcaption) {
            figcaption.append(copyButton[0]);
          } else {
            figure.prepend(copyButton[0]);
          }
        })

        var clipboard = new ClipboardJS('.clipboard-btn', {
          target: function(trigger) {
            return document.getElementById(trigger.getAttribute('data-clipboard-target-id'));
          }
        });
        clipboard.on('success', function(e) {
          e.clearSelection();
        })
      })
    </script>

    
    

    



<script src="/js/script.js"></script>


    
    <div class="searchbox ins-search">
    <div class="searchbox-mask"></div>
    <div class="searchbox-container ins-search-container">
        <div class="searchbox-input-wrapper">
            <input type="text" class="searchbox-input ins-search-input" placeholder="站内搜索" />
            <span class="searchbox-close ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="searchbox-result-wrapper ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: '文章',
                PAGES: '页面',
                CATEGORIES: '分类',
                TAGS: '标签',
                UNTITLED: '(无标题)',
            },
            CONTENT_URL: '/content.zh-cn.json',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>

<script src="/js/insight.js"></script>

    
</body>
</html>